/**
 * 自定义Editor.md编辑器配置
 * 扩展图片上传功能
 */
(function() {
    // 创建自定义图片上传对话框
    editormd.createDialog = function(options) {
        var defaults = {
            id        : "",
            container : "body",
            width     : 300,
            height    : 'auto',
            title     : "",
            closed    : true,
            drag      : true,
            lockScreen: true,
            mask      : true,
            maskStyle : {
                backgroundColor: "#000",
                opacity        : 0.3
            },
            buttons   : false
        };
        
        options     = $.extend(true, defaults, options);
        
        var $this   = this;
        var editor  = this.editor;
        var classPrefix = editormd.classPrefix;
        var guid    = new Date().getTime();
        var dialogID = ((options.id) ? options.id : classPrefix + "dialog-" + guid);
        var dialogName = dialogID;
        var dialog;
        
        if (options.closed)
        {
            dialog = $("<div class=\"" + classPrefix + "dialog " + dialogName + "\"></div>");
        }
        else 
        {
            dialog = $("#" + dialogID);
        }
        
        var dialogHeader = "<div class=\"" + classPrefix + "dialog-header\"";
        
        if (options.title) 
        {
            dialogHeader += " style=\"cursor: move;\"";
        }
        
        dialogHeader += ">";
        
        if (options.title)
        {
            dialogHeader += "<div class=\"" + classPrefix + "dialog-title\">" + options.title + "</div>";
        }
        
        dialogHeader += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a></div>";
        
        if (options.closed)
        {
            dialog.append(dialogHeader);
            
            dialog.append("<div class=\"" + classPrefix + "dialog-container\">" + options.content + "</div>");
            
            if (options.buttons && options.buttons.length > 0) 
            {
                var footer = "<div class=\"" + classPrefix + "dialog-footer\">";
                
                for (var i = 0, len = options.buttons.length; i < len; i++) 
                {
                    var btn = options.buttons[i];
                    var btnClassName = classPrefix + btn.className;
                    
                    footer += "<button class=\"" + btnClassName + "\" style=\"cursor: pointer;\">" + btn.label + "</button>";
                }
                
                footer += "</div>";
                
                dialog.append(footer);
            }
            
            $("body").append(dialog);
        }
        
        dialog.show();
        
        var dialogPos = dialog.position();
        
        if (options.lockScreen) 
        {
            $("html,body").css("overflow", "hidden");
        }
        
        if (options.mask) 
        {
            $("<div class=\"" + classPrefix + "mask\"></div>").css(options.maskStyle).appendTo(options.container);
        }
        
        dialog.css({
            top    : (dialogPos.top  - dialog.height() / 2 >= 0) ? dialogPos.top  - dialog.height() / 2 : 0,
            left   : (dialogPos.left - dialog.width() / 2  >= 0) ? dialogPos.left - dialog.width() / 2  : 0
        });
        
        if (options.drag && options.title)
        {
            var dialogHeader = $("." + classPrefix + "dialog-header", dialog);
            
            dialogHeader.css({
                cursor: "move"
            });
            
            dialogHeader.on("mousedown", function(e) {
                var dialogLeft   = dialog.position().left;
                var dialogTop    = dialog.position().top;
                
                var mouseLeft    = e.clientX - dialogLeft;
                var mouseTop     = e.clientY - dialogTop;
                
                $(document).on("mousemove", function(e) {
                    e = e || window.event;
                    
                    var left   = e.clientX - mouseLeft;
                    var top    = e.clientY - mouseTop;
                    
                    dialog.css({
                        left : left + "px",
                        top  : top  + "px"
                    });
                });
                
                $(document).on("mouseup", function() {
                    $(document).off("mousemove");
                    $(document).off("mouseup");
                });
            });
        }
        
        dialog.off("click", "." + classPrefix + "dialog-close").on("click", "." + classPrefix + "dialog-close", function() {
            options.closed = true;
            if (typeof options.onClose === "function") 
            {
                options.onClose();
            }
            
            close();
        });
        
        if (options.buttons && options.buttons.length > 0) 
        {
            for (var i = 0, len = options.buttons.length; i < len; i++) 
            {
                var btn = options.buttons[i];
                var btnClassName = "." + classPrefix + btn.className;
                
                dialog.off("click", btnClassName).on("click", btnClassName, (function(btn) {
                    return function() {
                        btn.callback();
                    };
                })(btn));
            }
        }
        
        $("." + classPrefix + "mask").css("z-index", parseInt($("." + classPrefix + "mask").css("z-index")) + 1).show();
        
        return {
            dialog : dialog,
            close  : close,
            show   : show
        };
        
        function close() {
            dialog.hide();
            $("." + classPrefix + "mask").fadeOut()
            setTimeout(function() {
                $("." + classPrefix + "mask").remove();  
            }, 500);
            
            if (options.lockScreen) 
            {
                $("html,body").css("overflow", "");
            }
            
            return this;
        }
        
        function show() {
            if (options.lockScreen) 
            {
                $("html,body").css("overflow", "hidden");
            }
            
            $("." + classPrefix + "mask").show();
            dialog.show();
            
            return this;
        }
    };
    
    // 加载图片上传插件
    editormd.loadPlugin = function(name, callback, into) {
        name = name.replace(/^[\/\\]?|\.[\/\\]?/g, "");
        
        var _name        = name;
        var basePath     = (into === "core") ? this.pluginPath : this.pluginExtPath;
        var scriptLoader = null;
        var scriptLoaded = false;
        var cmPathArr    = editormd.loadPlugins[name];
        var pluginPath   = basePath;
        
        if (cmPathArr && cmPathArr.length > 0)
        {
            pluginPath += ((cmPathArr.indexOf('.') === 0) ? cmPathArr : "/" + cmPathArr);
        }
        else
        {
            pluginPath += "/" + name + "/" + name;
        }
            
        if (typeof define === "function" && define.amd)
        {
            if (typeof requirejs !== "undefined")
            {
                requirejs.config({
                    baseUrl : "./",
                    paths : {
                        name : pluginPath
                    }
                });
                
                requirejs([name], function(cm) {
                    scriptLoaded = true;
                    callback(cm);
                });
            }
        }
        else
        {            
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src  = pluginPath + ".js";
            
            script.onload = script.onreadystatechange = function() {
                if(script.readyState) 
                {
                    if(script.readyState === "loaded" || script.readyState === "complete") 
                    {
                        script.onreadystatechange = null; 
                        
                        scriptLoaded = true;
                        
                        if (typeof callback === "function")
                        {
                            callback();
                        }
                    }
                } 
                else 
                {          
                    scriptLoaded = true;
                    
                    if (typeof callback === "function")
                    {
                        callback();
                    }
                }
            };
            
            document.body.appendChild(script);
        }
        
        return this;
    };

    // 初始化网站自定义编辑器
    window.initEditor = function(selector, options) {
        var defaults = {
            width: "100%",
            height: 500,
            path: "./dist/editor.md/lib/",
            markdown: "",
            codeFold: true,
            saveHTMLToTextarea: true,
            searchReplace: true,
            watch: true,
            htmlDecode: "style,script,iframe|on*",
            emoji: true,
            taskList: true,
            tocm: true,
            tex: true,
            flowChart: false,
            sequenceDiagram: false,
            placeholder: "开始创作...",
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "webp"],
            imageUploadURL: "/upload/image",
            toolbar: true,
            toolbarIcons: function() {
                return [
                    "undo", "redo", "|", 
                    "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|", 
                    "h1", "h2", "h3", "h4", "h5", "h6", "|", 
                    "list-ul", "list-ol", "hr", "|",
                    "link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
                    "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
                    "help", "info"
                ]
            },
            // 自定义图片上传
            onload: function() {
                var _this = this;
                var cm = this.cm;
                var editor = this.editor;
                var settings = this.settings;
                var langName = settings.lang.name;
                var lang = editormd.defaults.lang;

                // 图片上传事件
                $(editor).on("drop", function (e) {
                    // 阻止默认事件
                    e.preventDefault();
                    
                    // 获取拖拽的文件
                    var dataTransfer = e.originalEvent.dataTransfer;
                    var files = dataTransfer.files;
                    
                    // 验证文件是否为图片
                    if (files && files.length > 0) {
                        var isImage = false;
                        var imageIndex = 0;
                        
                        for (var i = 0; i < files.length; i++) {
                            var file = files[i];
                            
                            if (/^image\//.test(file.type)) {
                                isImage = true;
                                imageIndex = i;
                                break;
                            }
                        }
                        
                        if (isImage) {
                            // 上传图片
                            uploadImage(files[imageIndex]);
                        }
                    }
                });
                
                // 添加粘贴事件监听
                $(this.editor).on("paste", function(e) {
                    console.log("检测到粘贴事件");
                    var clipboardData = e.originalEvent.clipboardData;
                    
                    if (!clipboardData) {
                        console.log("无法访问剪贴板数据");
                        return;
                    }
                    
                    // 检查是否有图片
                    var items = clipboardData.items;
                    var imageItem = null;
                    
                    if (items) {
                        console.log("剪贴板包含 " + items.length + " 个项目");
                        for (var i = 0; i < items.length; i++) {
                            console.log("项目 " + i + ": " + items[i].type);
                            if (items[i].type.indexOf("image") !== -1) {
                                imageItem = items[i];
                                break;
                            }
                        }
                    }
                    
                    if (imageItem) {
                        e.preventDefault(); // 阻止默认粘贴行为
                        console.log("发现图片，准备上传");
                        
                        var file = imageItem.getAsFile();
                        if (file) {
                            // 显示上传中状态
                            settings.onloadFun();
                            
                            // 上传图片
                            uploadImage(file);
                        }
                    } else {
                        console.log("粘贴内容中没有图片");
                    }
                });

                // 自定义图片上传工具栏按钮处理
                this.setToolbar({
                    image: function() {
                        var dialog = editormd.createDialog({
                            title: "图片上传",
                            width: 380,
                            height: 250,
                            mask: true,
                            content: [
                                "<div class='editormd-form'>",
                                "<div class='editormd-form-group'>",
                                "<label>上传图片</label>",
                                "<input type='file' id='editormd-image-file' accept='image/*'>",
                                "</div>",
                                "<div class='editormd-form-group' style='margin-top: 10px;'>",
                                "<label>图片链接</label>",
                                "<input type='text' id='editormd-image-url' placeholder='或者输入图片链接'>",
                                "</div>",
                                "</div>"
                            ].join("\n"),
                            buttons: [
                                {
                                    className: "editormd-btn-primary",
                                    label: "确定",
                                    callback: function() {
                                        var fileInput = $("#editormd-image-file");
                                        var urlInput = $("#editormd-image-url");
                                        
                                        if (fileInput[0].files.length > 0) {
                                            // 上传图片文件
                                            uploadImage(fileInput[0].files[0]);
                                        } else if (urlInput.val() !== "") {
                                            // 使用图片链接
                                            var url = urlInput.val();
                                            var alt = "图片";
                                            
                                            _this.insertValue("![" + alt + "](" + url + ")");
                                            dialog.close();
                                        } else {
                                            alert("请选择图片文件或输入图片链接");
                                        }
                                    }
                                },
                                {
                                    className: "editormd-btn",
                                    label: "取消",
                                    callback: function() {
                                        dialog.close();
                                    }
                                }
                            ]
                        });
                    }
                });

                // 图片上传函数
                function uploadImage(file) {
                    var formData = new FormData();
                    formData.append("file", file);
                    
                    // 显示上传中提示
                    _this.settings.onloadFun();

                    $.ajax({
                        url: settings.imageUploadURL,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        dataType: "json",
                        success: function(data) {
                            if (data.code === 0) {
                                // 显示加载完成
                                _this.settings.onloadedFun();
                                
                                // 获取原始URL
                                var url = data.message;
                                var alt = file.name || "图片";
                                
                                console.log("服务器返回的URL: " + url);
                                
                                // 根据测试结果，使用以下任一URL格式都可以成功：
                                // 1. /upload/images/日期/文件名.jpg
                                // 2. /static/upload/images/日期/文件名.jpg
                                
                                // 添加时间戳防止缓存
                                var timestamp = new Date().getTime();
                                var finalUrl = url + "?t=" + timestamp;
                                
                                console.log("使用的最终URL: " + finalUrl);
                                
                                // 直接插入图片，不需要检查可访问性
                                _this.insertValue("![" + alt + "](" + finalUrl + ")");
                                
                                // 如果有对话框，关闭它
                                if (dialog) {
                                    dialog.close();
                                }
                                
                                // 如果有回调函数，执行它
                                if (settings.imageUploadCallback) {
                                    settings.imageUploadCallback(data);
                                }
                            } else {
                                // 显示加载完成
                                _this.settings.onloadedFun();
                                
                                // 上传失败处理
                                console.error("图片上传失败: " + data.message);
                                alert("图片上传失败: " + data.message);
                            }
                        },
                        error: function(xhr, textStatus, errorThrown) {
                            alert("图片上传失败: " + textStatus);
                            _this.settings.onloadedFun();
                        }
                    });
                }
            }
        };

        options = $.extend(true, defaults, options || {});
        
        // 添加加载提示回调
        options.onloadFun = options.onloadFun || function() {};
        options.onloadedFun = options.onloadedFun || function() {};
        
        return editormd(selector, options);
    };
})(); 

// 处理图片URL的辅助函数
function processImageUrl(url) {
    // 添加时间戳防止缓存
    var timestamp = "?t=" + new Date().getTime();
    
    // 转换URL格式，确保可以正确访问
    if (url.startsWith("/upload/images/")) {
        // 解析日期和文件名
        var parts = url.split("/");
        if (parts.length >= 4) {
            var date = parts[2];
            var filename = parts[3];
            
            // 使用直接访问端点
            var directUrl = "/upload/file/" + date + "/" + filename + timestamp;
            console.log("生成直接访问URL: " + directUrl);
            return directUrl;
        }
    }
    
    return url + timestamp;
}

// 获取备用图片URL
function getBackupImageUrl(originalUrl) {
    if (originalUrl.startsWith("/upload/images/")) {
        // 解析日期和文件名
        var parts = originalUrl.split("/");
        if (parts.length >= 4) {
            var date = parts[2];
            var filename = parts[3];
            
            // 返回不带时间戳的直接访问URL
            return "/upload/file/" + date + "/" + filename;
        }
    }
    return originalUrl;
} 